package cn.joker.springsecurity.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * @author : jwp
 * @description : 自定义用户详情服务实现类
 * @createDate : 2025/2/8 10:37
 */
@Service
public class UserDetailsImpl implements UserDetailsService {


    @Autowired
    private PasswordEncoder pw;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("执行了loadUserByUsername方法");

       //1.查询数据库判断用户名是否存在 如果不存在抛出异常 UsernameNotFoundException
        if(!"admin".equals(username)) {
            throw new UsernameNotFoundException("用户名: "+username+"不存在");
        }
       //2.把查询的密码（注册时已经加密过）进行解析，或者直接把密码放入构造方法中
        String password = pw.encode("123456");
        return new User(username,password, AuthorityUtils.createAuthorityList("admin","normal"));
    }
}
